package com.beta.springmvc.controller;

import com.beta.springmvc.model.Person;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.portlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Created by yaoyt on 16/12/1.
 *
 * @author yaoyt
 */
@Controller
public class HelloController {

    @RequestMapping("/hello")
    public String hello(){
        System.out.println("hello world");
        return "hello";
    }

    @RequestMapping("/person")   // http://localhost:8080/person?name=yaoyt&age=14
    public String toPerson(String name,double age){
        System.out.println(name+" "+age);
        return "hello";
    }

    @RequestMapping("/person1")
    // http://localhost:8080/person1?name=yaoyt&age=14
    // http://localhost:8080/person1?person.name=yaoyt&person.age=14   无效
    // http://localhost:8080/person1?p.name=yaoyt&p.age=14   无效
    public String toPerson(Person p){
        System.out.println(p.getName()+" "+p.getAge());
        return "hello";
    }

    //the parameter was converted in initBinder
    //http://localhost:8080/date?date=2016-11-13
    @RequestMapping("/date")
    public String date(Date date){
        System.out.println(date);
        return "hello";
    }

    //At the time of initialization,convert the type "String" to type "date"
    @InitBinder
    public void initBinder(ServletRequestDataBinder binder){
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }

    //pass the parameters to front-end
    //http://localhost:8080/show
    // map 是必须要有的,负责传参
    @RequestMapping("/show")
    public String showPerson(Map<String,Object> map){
        Person p =new Person();
        map.put("p", p);
        p.setAge(20);
        p.setName("jayjay");
        return "show";
    }


    //pass the parameters to front-end using ajax
    @RequestMapping("/name")
    public String sayHello(){ return "name"; }
    @RequestMapping("/getPerson")
    public void getPerson(String name,PrintWriter pw){
        pw.write("hello,"+name);
    }

    //redirect
    //http://localhost:8080/redirect
    @RequestMapping("/redirect")
    public String redirect(){ return "redirect:hello"; }

    //upload file
    @RequestMapping("/file")
    public String showFileUploadPage(){
        return "file";
    }
    @RequestMapping(value="/upload",method= RequestMethod.POST)
    public String upload(HttpServletRequest req) throws Exception{
        MultipartHttpServletRequest mreq = (MultipartHttpServletRequest)req;
        MultipartFile file = mreq.getFile("file");
        String fileName = file.getOriginalFilename();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        File newFile = new File(req.getSession().getServletContext().getRealPath("/")
                + "upload/"+sdf.format(new Date())+fileName.substring(fileName.lastIndexOf('.')));
        if(newFile.exists()){//如果已经存在
            newFile.delete();//删除之
        }
        //判断目标文件所在的目录是否存在
        if(!newFile.getParentFile().exists()) {
            //如果目标文件所在的目录不存在，则创建父目录
            System.out.println("目标文件所在目录不存在，准备创建它！");
            if(!newFile.getParentFile().mkdirs()) {
                System.out.println("创建目标文件所在目录失败！");
            }
        }
        newFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(newFile);
        fos.write(file.getBytes());
        fos.flush();
        fos.close();
        return "hello";
    }

    // 使用 RequestParam 指定参数的 传参name
    // http://localhost:8080/param?id1=123&name1=abc
    // http://localhost:8080/param?id=123&name=abc 无效
    @RequestMapping(value="/param")
    public String testRequestParam(@RequestParam(value="id1") Integer id, @RequestParam(value="name1")String name){
        System.out.println(id+" "+name);
        return "/hello";
    }

    @RequestMapping("/error")
    public String error() {
        int i = 5 / 0;
        return "hello";
    }

    @ExceptionHandler
    public ModelAndView exceptionHandler(Exception ex) {
        ModelAndView mv = new ModelAndView("error");
        mv.addObject("exception", ex);
        System.out.println("in testExceptionHandler");
        return mv;
    }







}
